package com.czy.blog.service;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class MyRealm extends AuthorizingRealm{

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		String username = (String) principal.fromRealm(getName()).iterator().next(); 
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		if(StringUtils.equals("user1", username)){
			info.addStringPermission("a");
			info.addStringPermission("b");
		}else if(StringUtils.equals("user2", username)){
			info.addStringPermission("a");
		}
		
		return info;
	}

	/**
	 * 认证回调函数,登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authToken) throws AuthenticationException {
		
		UsernamePasswordToken token = (UsernamePasswordToken)authToken;
		String username = token.getUsername();
		
		if(StringUtils.isBlank(username)){
			return null;
		}
		
		return new SimpleAuthenticationInfo(username, token.getPassword(), getName());
	}
}
